<?php

App::uses('AppController', 'Controller');

/**
 * CoreBlocks Controller
 *
 * @property CoreBlock $CoreBlock
 */
class CoreBlocksController extends AppController {

    static $iconCls = "block";

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->CoreBlock->recursive = 0;
        $this->set('coreBlocks', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->CoreBlock->exists($id)) {
            throw new NotFoundException(__('Invalid core block'));
        }
        $options = array('conditions' => array('CoreBlock.' . $this->CoreBlock->primaryKey => $id));
        $this->set('coreBlock', $this->CoreBlock->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->CoreBlock->create();
            if (!empty($_POST['cobl_attributes'])) {
                $this->request->data["CoreBlock"]['cobl_attributes'] = serialize($_POST['cobl_attributes']);
            }
            if ($this->CoreBlock->save($this->request->data)) {
                //$this->getInsertID();
                $id = $this->CoreBlock->getInsertID();
                App::import('Model', 'CoreBlocksModule');
                $coreBlocksModule = new CoreBlocksModule();
                $coreBlocksModule->create();
                // delete all modules for this block
                $data = array('CoreBlocksModule.core_blocks_id' => $id);
                // delete the data
                $coreBlocksModule->deleteAll($data);
                // save each module
                if (!empty($this->request->data["CoreModule"]["como_id"])) {
                    foreach ($this->request->data["CoreModule"]["como_id"] as $value) {
                        if(empty($value)) continue;
                        $coreBlocksModule->create();
                        $data = array(
                            'CoreBlocksModule' => array(
                                'core_modules_id' => $value,
                                'core_blocks_id' => $id
                            )
                        );
                        // save the data
                        $coreBlocksModule->save($data);
                    }
                }

                App::import('Model', 'CoreGroupsBlock');
                $coreGroupsBlock = new CoreGroupsBlock();
                $coreGroupsBlock->create();
                // delete all modules for this block
                $data = array('CoreGroupsBlock.core_blocks_id' => $id);
                // delete the data
                $coreGroupsBlock->deleteAll($data);
                // save each Group
                if (!empty($this->request->data["CoreGroupsBlock"]["core_groups_id"])) {
                    foreach ($this->request->data["CoreGroupsBlock"]["core_groups_id"] as $value) {
                        if(empty($value)) continue;
                        $coreGroupsBlock->create();
                        $data = array(
                            'CoreGroupsBlock' => array(
                                'core_groups_id' => $value,
                                'core_blocks_id' => $id
                            )
                        );
                        // save the data
                        $coreGroupsBlock->save($data);
                    }
                }
                $this->Session->setFlash(__('The core block has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core block could not be saved. Please, try again.'));
            }
        }
        App::import('Controller', 'CoreModules');
        $coreModule = new CoreModulesController();
        $modules = $coreModule->listModulesFromDB();
        $this->set(compact('modules'));
        $blocksArray = $this->listAllBlocksArray();
        $this->set(compact('blocksArray'));
        $coreSites = $this->CoreBlock->CoreSites->find('list', array('fields' => array('CoreSites.id', 'CoreSites.cosi_name')));
        $this->set(compact('coreSites'));

        App::import('Controller', 'CoreGroups');
        $coreGroups = new CoreGroupsController();
        $groups = $coreGroups->listGroupsFromDB();
        $this->set(compact('groups'));
        
        $this->set('layouts', $this->listLayouts());
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->CoreBlock->exists($id)) {
            throw new NotFoundException(__('Invalid core block'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if (!empty($_POST['cobl_attributes'])) {
                $this->request->data["CoreBlock"]['cobl_attributes'] = serialize($_POST['cobl_attributes']);
            }
            if ($this->CoreBlock->save($this->request->data)) {
                //var_dump($this->request->data);exit;
                // save modules
                App::import('Model', 'CoreBlocksModule');
                $coreBlocksModule = new CoreBlocksModule();
                $coreBlocksModule->create();
                // delete all modules for this block
                $data = array('CoreBlocksModule.core_blocks_id' => $id);
                // delete the data
                $coreBlocksModule->deleteAll($data);
                // save each module
                if (!empty($this->request->data["CoreModule"]["como_id"])) {
                    foreach ($this->request->data["CoreModule"]["como_id"] as $value) {
                        if(empty($value)) continue;
                        $coreBlocksModule->create();
                        $data = array(
                            'CoreBlocksModule' => array(
                                'core_modules_id' => $value,
                                'core_blocks_id' => $id
                            )
                        );
                        // save the data
                        $coreBlocksModule->save($data);
                    }
                }

                App::import('Model', 'CoreGroupsBlock');
                $coreGroupsBlock = new CoreGroupsBlock();
                $coreGroupsBlock->create();
                // delete all modules for this block
                $data = array('CoreGroupsBlock.core_blocks_id' => $id);
                // delete the data
                $coreGroupsBlock->deleteAll($data);
                // save each Group
                if (!empty($this->request->data["CoreGroupsBlock"]["core_groups_id"])) {
                    foreach ($this->request->data["CoreGroupsBlock"]["core_groups_id"] as $value) {
                        if(empty($value)) continue;
                        $coreGroupsBlock->create();
                        $data = array(
                            'CoreGroupsBlock' => array(
                                'core_groups_id' => $value,
                                'core_blocks_id' => $id
                            )
                        );
                        // save the data
                        $coreGroupsBlock->save($data);
                    }
                }
                $this->Session->setFlash(__('The core block has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core block could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('CoreBlock.' . $this->CoreBlock->primaryKey => $id));
            $this->request->data = $this->CoreBlock->find('first', $options);
        }
        App::import('Controller', 'CoreBlocksModules');
        $coreBlocksModule = new CoreBlocksModulesController();
        $modulesSelected = $coreBlocksModule->getModulesIdFromBlock($id);
        //$selected = array(2,4);
        $this->set(compact('modulesSelected'));
        App::import('Controller', 'CoreModules');
        $coreModule = new CoreModulesController();
        $modules = $coreModule->listModulesFromDB();
        $this->set(compact('modules'));
        $blocksArray = $this->listAllBlocksArray();
        $this->set(compact('blocksArray'));
        $coreSites = $this->CoreBlock->CoreSites->find('list', array('fields' => array('CoreSites.id', 'CoreSites.cosi_name')));
        $this->set(compact('coreSites'));


        App::import('Controller', 'CoreGroupsBlocks');
        $coreGroupsBlocks = new CoreGroupsBlocksController();
        $groupsSelected = $coreGroupsBlocks->getGroupsIdFromBlock($id);
        $this->set(compact('groupsSelected'));
        App::import('Controller', 'CoreGroups');
        $coreGroups = new CoreGroupsController();
        $groups = $coreGroups->listGroupsFromDB();
        $this->set(compact('groups'));
        
        $this->set('layouts', $this->listLayouts());
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->CoreBlock->id = $id;
        if (!$this->CoreBlock->exists()) {
            throw new NotFoundException(__('Invalid core block'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->CoreBlock->delete()) {
            $this->Session->setFlash(__('Core block deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Core block was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

    private function listAllBlocksArray() {
        $blocks = $this->listAllBlocks();
        $list = array();
        foreach ($blocks as $moduleName => $blocksArray) {
            if (!empty($blocksArray)) {
                foreach ($blocksArray as $blocksName) {
                    $list["{$moduleName}/{$blocksName}"] = str_replace("_", " ", "{$moduleName}/{$blocksName}");
                }
            }
        }
        //var_dump($list);
        return $list;
    }

    private function listAllBlocks() {
        App::import('Controller', 'CoreModules');
        $coreModule = new CoreModulesController();
        $modules = $coreModule->listModules();
        $modulesAndBlocks = array();
        foreach ($modules as $value) {
            $modulesAndBlocks[$value] = $this->listBlocks($value);
        }
        return $modulesAndBlocks;
    }

    public function listBlocks($className) {
        App::import('Controller', $className);
        $methods = get_class_methods($className . "Controller");
        $blocks = array();
        if($methods){
            foreach ($methods as $val) {
                preg_match('/^(block_.+)$/i', $val, $matches);
                if (!empty($matches)) {
                    $blocks[] = $matches[1];
                }
            }
        }
        return $blocks;
    }

    /**
     * show a block for ajax
     * @param int $blockId
     * @throws NotFoundException
     */
    public function loadBlock($blockId) {
        echo $this->returnBlock($blockId);
    }

    /**
     * show a block for ajax
     * @param int $blockId
     * @throws NotFoundException
     */
    private function returnBlock($blockId) {
        $this->CoreBlock->id = $blockId;
        if (!$this->CoreBlock->exists()) {
            throw new NotFoundException(__('Invalid core block'));
        }
        $options = array(
            'conditions' => array(
                'CoreBlock.' . $this->CoreBlock->primaryKey => $blockId,
                'CoreBlock.cobl_status' => 'a'
            ),
            'order' => array(
                'CoreBlock.cobl_sequence' => 'ASC'
            ),
            'fields' => array(
                'CoreBlock.id',
                'CoreBlock.cobl_name',
                'CoreBlock.cobl_position',
                'CoreBlock.cobl_template',
                'CoreBlock.cobl_attributes',
                'CoreBlock.cobl_description'
        ));
        $data = $this->CoreBlock->find('first', $options);
        // TODO verificar se tem permissao pra acessar o modulo
        if (empty($data["CoreBlock"])) {
            return "";
        }
        $block = $data["CoreBlock"];
        $controller = explode("/", $block["cobl_name"]);
        $this->set(compact('block'));
        $layoutBefore = $this->layout;
        if(empty($block["cobl_template"])){
            $this->layout = 'ajax';
        }else{
            $this->layout = substr($block["cobl_template"], 0, -4);
        }
        // check if the controllef file exists
        if(file_exists(APP.DS."Controller".DS."{$controller[0]}Controller.php")){
        $action = $this->requestAction(
                    array('controller' => $controller[0], 'action' => $controller[1], $blockId),
                    array(
                           'return',
                           'bare' => true
                       )        
                );
        $this->layout = $layoutBefore;
        return $action;
        }else{
            return '';
        }
    }

    /**
     * 
     * @param type $site
     * @param type $position
     * @param type $moduleId if moduleId = -1 load all blocks
     * @return type
     */
    private function getAllBlocks($site, $position, $moduleId) {
        $this->CoreBlock->create();
        return $this->CoreBlock->find('all', $this->getOptions($site, $position, $moduleId));
    }

    private function getOptions($site, $position, $moduleId) {
        $user = $this->Session->read('user');

        if ($moduleId == -1) {
            $options = array(
                'joins' => array(
                    array(
                        'table' => 'core_blocks_modules',
                        'alias' => 'module',
                        'type' => 'INNER',
                        'conditions' => array(
                            'module.core_blocks_id = CoreBlock.id'
                        )
                    )
                ),
                'conditions' => array(
                    'CoreBlock.core_sites_id' => $site,
                    'CoreBlock.cobl_position' => $position
                ),
                'order' => array(
                    'CoreBlock.cobl_sequence' => 'ASC'
                ),
                'fields' => array(
                    'CoreBlock.id',
                    'CoreBlock.cobl_name',
                    'CoreBlock.cobl_position',
                    'CoreBlock.cobl_template',
                    'CoreBlock.cobl_attributes',
                    'CoreBlock.cobl_status',
                    'CoreBlock.cobl_description'
                ),
                'group' => 'CoreBlock.id'
                );
        } else {
            if(!empty($user['groups']) && is_array($user['groups']) && !empty($user['groups'][0])){
                $s = 'group.core_groups_id IN (' . implode(', ', $user['groups']) . ')';
            }else{
                $s = '';
            }
            $options = array(
                'joins' => array(
                    array(
                        'table' => 'core_blocks_modules',
                        'alias' => 'module',
                        'type' => 'INNER',
                        'conditions' => array(
                            'module.core_modules_id' => $moduleId,
                            'module.core_blocks_id = CoreBlock.id'
                        )
                    ),
                    array(
                        'table' => 'core_groups_blocks',
                        'alias' => 'group',
                        'type' => 'INNER',
                        'conditions' => array(
                            $s,
                            'group.core_blocks_id = CoreBlock.id'
                        )
                    )
                ),
                'conditions' => array(
                    'CoreBlock.core_sites_id' => $site,
                    'CoreBlock.cobl_position' => $position,
                    'CoreBlock.cobl_status' => 'a'
                ),
                'order' => array(
                    'CoreBlock.cobl_sequence' => 'ASC'
                ),
                'fields' => array(
                    'CoreBlock.id',
                    'CoreBlock.cobl_name',
                    'CoreBlock.cobl_position',
                    'CoreBlock.cobl_template',
                    'CoreBlock.cobl_attributes',
                    'CoreBlock.cobl_status',
                    'CoreBlock.cobl_description'
                ),
                'group' => 'CoreBlock.id');
        }
        return $options;
    }

    private function getAllBlocksContent($site, $position, $moduleId) {
        $blocks = $this->getAllBlocks($site, $position, $moduleId);
        $returnBlocks = array();
        foreach ($blocks as $value) {
            $returnBlocks[] = $this->returnBlock($value["CoreBlock"]["id"]);
        }
        return $returnBlocks;
    }

    public function getArrayBlocks($moduleId) {
        $this->CoreBlock->setBypass(true);
        $site = 1; // TODO pegar o site da sessao
        $blocks = array();
        // blocks from top
        $blocks['t'] = $this->getAllBlocksContent($site, 't', $moduleId);

        // blocks from left
        $blocks['l'] = $this->getAllBlocksContent($site, 'l', $moduleId);

        // blocks from center
        $blocks['c'] = $this->getAllBlocksContent($site, 'c', $moduleId);

        // blocks from right
        $blocks['r'] = $this->getAllBlocksContent($site, 'r', $moduleId);

        // blocks from bottom
        $blocks['b'] = $this->getAllBlocksContent($site, 'b', $moduleId);

        $this->CoreBlock->setBypass(false);
        return $blocks;
    }

    static $block_edit_iconCls = "block--pencil";
    public function block_edit() {
        // TODO pegar o site da sessao
        $site = 1;
        $moduleId = -1;
        $blocks = array();
        $blocks['t'] = $this->getAllBlocks($site, 't', $moduleId);
        $blocks['l'] = $this->getAllBlocks($site, 'l', $moduleId);
        $blocks['c'] = $this->getAllBlocks($site, 'c', $moduleId);
        $blocks['r'] = $this->getAllBlocks($site, 'r', $moduleId);
        $blocks['b'] = $this->getAllBlocks($site, 'b', $moduleId);
        $this->set("editBlocks", $blocks);
    }
    
    function saveBlocks(){
        //var_dump($_POST["coreBlock"]);exit;
        foreach ($_POST["coreBlock"] as $key => $value) {
            $this->CoreBlock->save($value);
        }
        echo "true";exit;
    }
    
    static $block_html_iconCls = "validation-label-html";
    public function block_html($id = null) {
        $this->setBlocksAttributes($id);
    }
    
    function form_block_html($id = null){
        $this->setBlocksAttributes($id);
    }
    
    static $block_raw_text_iconCls = "application-text";
    public function block_raw_text($id = null) {
        $this->setBlocksAttributes($id);
    }
    
    function form_block_raw_text($id = null){
        $this->setBlocksAttributes($id);
    }

}
